package com.hiwan.platform.util;

import java.nio.ByteBuffer;

public class ByteBufferReader {
	private ByteBuffer buffer;

	public ByteBufferReader(ByteBuffer buffer) {
		this.buffer = buffer;
	}
	
	public ByteBufferReader(byte[] bytes) {
		this.buffer = ByteBuffer.wrap(bytes);
	}

	/***
	 * 从ByteBuffer中读取指定长度的字符串
	 * @param size 要读取的字符串长度
	 * @param charSet 编码字符集，若不支持该字符集则返回null
	 * @return 读取的字符串
	 * @throws Exception 
	 */
	public String readString(int size, String charSet) throws Exception {
		byte[] bytes = new byte[size];
		buffer.get(bytes);
		return new String(bytes, charSet).trim();
	}

	public int readInt() {
		byte[] bytes = new byte[4];
		buffer.get(bytes);
		return Integer.valueOf(new String(bytes).trim());
	}

	public byte[] readBytes(int size) {
		byte[] bytes = new byte[size];
		buffer.get(bytes);
		return bytes;
	}

	public ByteBuffer getBuffer() {
		return buffer;
	}

	public void setBuffer(ByteBuffer buffer) {
		this.buffer = buffer;
	}

}
